package com.lovemanai.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lovemanai.listener.MyReadListener;

@WebServlet(urlPatterns="/async2", asyncSupported=true)
public class AsyncServlet2 extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<h2>进入异步处理的时间：</h2>");
		out.println("" + new Date() + "<br/>");
		/*
		 * Servlet异步处理是让Servlet重新发起一个线程用以处理耗时的业务，达到避免等待的效果
		 */
		//获得AsyncContext对象，开始异步调用
		AsyncContext actx = request.startAsync();
		//设置异步调用超时等待时间
		actx.setTimeout(1000 * 6);
		//获得输入流
		ServletInputStream input = request.getInputStream();
		//为输入流注册监听器
		input.setReadListener(new MyReadListener(input,actx));
		System.out.println(input);
		out.println("<h2>结束异步处理的时间：</h2>");
		out.println("" + new Date() + "<br/>");
		out.flush();
	}
	
	
}
